// pages/wallet/index.js
const api = require('../../utils/api');
const utils = require('../../utils/index');

Page({
  data: {
    tabActive: 0, // 默认显示团购券标签页
    groupBuyList: [], // 团购券列表
    couponList: [], // 优惠券列表
    isLoading: false, // 加载状态
    showStoreModal: false, // 是否显示可用门店模态框
    currentUsageRange: null, // 当前查看的团购券使用范围
  },

  onLoad: function(options) {
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: '我的卡包',
    });

    // 如果有传入的标签页参数，则切换到对应标签页
    if (options.tabIndex) {
      this.setData({
        tabActive: parseInt(options.tabIndex)
      });
    }

    // 加载数据
    this.loadData();
  },
  
  // 显示页面时刷新数据
  onShow: function() {
    this.loadData();
  },

  // 加载数据
  loadData: function() {
    this.setData({ isLoading: true });
    
    // 加载团购券数据
    this.loadGroupBuyData();
    
    // 加载优惠券数据
    this.loadCouponData();
  },
  
  // 加载团购券数据
  loadGroupBuyData: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    api.groupBuy.getMyGroupBuy()
      .then(res => {
        if (res && res.success) {
          // 处理数据，格式化日期等
          const groupBuyList = (res.data || []).map(item => {
            // 检查是否过期
            const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
            const validUntil = item.valid_until || item.end_time || 0;
            const isExpired = validUntil < currentTime;
            
            let formatted_weekdays = '';
            if (item.available_weekdays) {
              try {
                const weekdays = JSON.parse(item.available_weekdays);
                const weekdayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                formatted_weekdays = weekdays.map(day => weekdayMap[day]).join('、');
              } catch (e) {}
            }

            let formatted_times = '';
            if (item.available_times) {
              try {
                const times = JSON.parse(item.available_times);
                formatted_times = times.map(t => `${t.start_time}-${t.end_time}`).join('; ');
              } catch (e) {}
            }

            return {
              ...item,
              validDate: utils.formatTimestamp(validUntil),
              isExpired: isExpired,
              statusText: isExpired ? "已过期" : "可使用",
              rulesVisible: false, // 默认隐藏规则
              description: item.description || '具体使用规则以门店为准',
              formatted_weekdays: formatted_weekdays,
              formatted_times: formatted_times
            };
          });
          
          this.setData({
            groupBuyList: groupBuyList
          });
        } else {
          console.error('获取团购券失败:', res);
          this.setData({
            groupBuyList: []
          });
        }
      })
      .catch(err => {
        console.error('获取团购券失败:', err);
        this.setData({
          groupBuyList: []
        });
      })
      .finally(() => {
        wx.hideLoading();
        this.setData({ isLoading: false });
      });
  },
  
  // 加载优惠券数据
  loadCouponData: function() {
    api.coupon.getMyCoupons()
      .then(res => {
        if (res && res.success) {
          // 处理数据，格式化日期等
          const couponList = (res.data || []).map(item => {
            // 检查是否过期
            const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
            const validUntil = item.valid_until || item.end_time || 0;
            const isExpired = validUntil < currentTime;

            let formatted_weekdays = '';
            if (item.available_weekdays) {
              try {
                const weekdays = JSON.parse(item.available_weekdays);
                const weekdayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                formatted_weekdays = weekdays.map(day => weekdayMap[day]).join('、');
              } catch (e) {}
            }

            let formatted_times = '';
            if (item.available_times) {
              try {
                const times = JSON.parse(item.available_times);
                formatted_times = times.map(t => `${t.start_time}-${t.end_time}`).join('; ');
              } catch (e) {}
            }
            
            return {
              ...item,
              validDate: utils.formatTimestamp(validUntil),
              condition: `满${item.min_consume}元可用`,
              isExpired: isExpired,
              statusText: isExpired ? "已过期" : "可使用",
              typeText: this.getCouponTypeText(item.type), // 将类型代码转换为文字
              formatted_weekdays: formatted_weekdays,
              formatted_times: formatted_times,
              usageRangeText: '加载中...'
            };
          });
          
          this.setData({
            couponList: couponList
          });

          // 为每个优惠券获取使用范围
          couponList.forEach((coupon, index) => {
            if (coupon.applicable_type !== 0) { // 0表示全场通用
              this.getCouponUsageRange(coupon.id, index);
            }
          });

        } else {
          console.error('获取优惠券失败:', res);
          this.setData({
            couponList: []
          });
        }
      })
      .catch(err => {
        console.error('获取优惠券失败:', err);
        this.setData({
          couponList: []
        });
      });
  },

  // 获取优惠券使用范围
  getCouponUsageRange: function(id, index) {
    api.coupon.getUsageRange(id)
      .then(res => {
        if (res && res.success && res.data) {
          const couponList = this.data.couponList;
          let usageRangeText = '';
          if (res.data.stores && res.data.stores.length > 0) {
            usageRangeText = '指定门店可用：' + res.data.stores.map(s => s.name).join('、');
          } else if (res.data.venues && res.data.venues.length > 0) {
            usageRangeText = '指定场地可用：' + res.data.venues.map(v => v.name).join('、');
          }
          if (couponList[index]) {
            couponList[index].usageRangeText = usageRangeText;
            this.setData({ couponList });
          }
        } else {
          const couponList = this.data.couponList;
          if (couponList[index]) {
            couponList[index].usageRangeText = '获取使用范围失败';
            this.setData({ couponList });
          }
        }
      })
      .catch(err => {
        console.error('获取优惠券使用范围失败:', err);
        const couponList = this.data.couponList;
        if (couponList[index]) {
          couponList[index].usageRangeText = '获取使用范围失败';
          this.setData({ couponList });
        }
      });
  },

  // 将优惠券类型代码转换为文字描述
  getCouponTypeText: function(type) {
    const typeMap = {
      0: '折扣券',
      1: '现金券',
      2: '满减券',
      3: '时长券',
      4: '免费券',
      5: '赠品券',
      6: '特价券'
    };
    
    return typeMap[type] || '未知类型';
  },

  // 切换标签页
  onTabChange: function(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      tabActive: index
    });
  },

  // 返回上一页
  onTapBack: function(e) {
    console.log("onTapBack:")
    wx.navigateBack();
  },

  // 使用团购券
  onUseGroupBuy: function(e) {
    const id = e.currentTarget.dataset.id;
    const groupBuyItem = this.data.groupBuyList.find(item => item.id === id);

    if (!groupBuyItem) {
      wx.showToast({
        title: '未找到该团购券',
        icon: 'none'
      });
      return;
    }

    if (groupBuyItem.isExpired) {
      wx.showToast({
        title: '该团购券已过期',
        icon: 'none'
      });
      return;
    }

    const now = new Date();
    const currentDay = now.getDay(); // 0 for Sunday, 1 for Monday, ..., 6 for Saturday
    const currentTime = now.getHours() * 100 + now.getMinutes(); // e.g., 14:30 is 1430

    let availableWeekdays = [];
    try {
      if (groupBuyItem.available_weekdays) {
        availableWeekdays = JSON.parse(groupBuyItem.available_weekdays);
      }
    } catch (error) {
      console.error('Error parsing available_weekdays:', error);
    }

    let availableTimes = [];
    try {
      if (groupBuyItem.available_times) {
        availableTimes = JSON.parse(groupBuyItem.available_times);
      }
    } catch (error) {
      console.error('Error parsing available_times:', error);
    }

    // Check weekday availability
    if (availableWeekdays.length > 0 && !availableWeekdays.includes(currentDay)) {
      wx.showToast({
        title: '今天不可使用该券',
        icon: 'none'
      });
      return;
    }

    // Check time availability
    if (availableTimes.length > 0) {
      const isTimeAvailable = availableTimes.some(timeRange => {
        const startTime = parseInt(timeRange.start_time.replace(':', ''), 10);
        const endTime = parseInt(timeRange.end_time.replace(':', ''), 10);
        return currentTime >= startTime && currentTime <= endTime;
      });

      if (!isTimeAvailable) {
        wx.showToast({
          title: '当前时段不可用',
          icon: 'none'
        });
        return;
      }
    }

    wx.redirectTo({
      url: `/pages/venue/timeslot?groupbuy_id=${id}`,
      complete: (res) => {
        console.log("onUseGroupBuy:", res)
      }
    });
  },

  // 使用优惠券
  onUseCoupon: function(e) {
    const id = e.currentTarget.dataset.id;
    const isExpired = e.currentTarget.dataset.expired;
    
    if (isExpired) {
      wx.showToast({
        title: '该优惠券已过期',
        icon: 'none'
      });
      return;
    }
    
    wx.redirectTo ({
      url: `/pages/venue/timeslot?coupon_id=${id}`
    });
  },

  // 切换规则显示
  toggleRules: function(e) {
    const id = e.currentTarget.dataset.id;
    const groupBuyList = this.data.groupBuyList.map(item => {
      if (item.id === id) {
        item.rulesVisible = !item.rulesVisible;
      }
      return item;
    });
    this.setData({ groupBuyList });
  },

  // 切换优惠券规则显示
  toggleCouponRules: function(e) {
    const id = e.currentTarget.dataset.id;
    const couponList = this.data.couponList.map(item => {
      if (item.id === id) {
        item.rulesVisible = !item.rulesVisible;
      }
      return item;
    });
    this.setData({ couponList });
  },

  // 切换可用门店模态框
  toggleStoreModal: function(e) {
    const groupBuyId = e.currentTarget.dataset.id;
    // 先切换弹窗状态
    this.setData({
      showStoreModal: !this.data.showStoreModal
    });
    // 如果是打开弹窗并且有ID，获取使用范围数据
    if (this.data.showStoreModal && groupBuyId) {
      this.getGroupBuyUsageRange(groupBuyId);
    }
  },

  // 获取团购券使用范围
  getGroupBuyUsageRange: function(id) {
    wx.showLoading({
      title: '加载中...'
    });
    
    api.groupBuy.getUsageRange(id)
      .then(res => {
        if (res && res.success && res.data) {
          this.setData({
            currentUsageRange: res.data
          });
        } else {
          console.error('获取团购券使用范围失败:', res);
          wx.showToast({
            title: '获取使用范围失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取团购券使用范围失败:', err);
        wx.showToast({
          title: '获取使用范围失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 团购券核销
  onTapVerify: function() {
    wx.navigateTo({
      url: '/pages/coupon/verify'
    });
  },

  // 积分兑换
  onTapExchange: function() {
    // 跳转到优惠券页面并显示积分标签页
    wx.setStorageSync('couponTabIndex', 2);
    wx.reLaunch({
      url: '/pages/coupon/index',
      success: function() {
      }
    });
  },

  // 购买团购券
  onTapBuyGroupon: function() {
    // 跳转到优惠券页面并显示团购券标签页
    wx.setStorageSync('couponTabIndex', 1);
    wx.reLaunch({
      url: '/pages/coupon/index',
      success: function() {
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.loadData();
    wx.stopPullDownRefresh();
  },

  onShareAppMessage: function() {
    // 自定义分享内容
    return {
      title: '共享空间 - 我的卡包',
      path: '/pages/wallet/index',
      imageUrl: '/images/share_image.png' // 分享图片
    };
  }
});